package com.spr.gw.service.impl;

import com.spr.gw.common.EnumCode;
import com.spr.gw.entity.SystemLog;
import com.spr.gw.entity.User;
import com.spr.gw.mapper.SystemLogMapper;
import com.spr.gw.service.SystemLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by lsy
 * on 2017/10/20 17:21.
 */
@Slf4j
@Service
public class SystemLogServiceImpl implements SystemLogService {

    @Autowired
    private SystemLogMapper systemLogMapper;

    public void recordLog(HttpServletRequest request, String operation, String content){
        String ip = getLocalIp(request);
        User user = (User)request.getSession().getAttribute(EnumCode.LOGIN_USER.getValue());
        SystemLog systemLog = SystemLog.builder().content(content).createTime(new Date()).ipAddress(ip).operation(operation).build();
        int insert = systemLogMapper.insert(systemLog);
    }






    private  String getLocalIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");

        String ip = null;
        if (realIp == null) {
            if (forwarded == null) {
                ip = remoteAddr;
            } else {
                ip = remoteAddr + "/" + forwarded.split(",")[0];
            }
        } else {
            if (realIp.equals(forwarded)) {
                ip = realIp;
            } else {
                if(forwarded != null){
                    forwarded = forwarded.split(",")[0];
                }
                ip = realIp + "/" + forwarded;
            }
        }
        return ip;
    }
}
